<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\UserTable;
use App\Admin\Repositories\Firm;
use App\Models\FirmCategory;
use App\Models\FirmProfession;
use App\Models\Message;
use App\Models\User;
use App\Services\TtsService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;

class FirmController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Firm(['user:id,nickname,avatar','profession:id,name','category:id,name']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('user.avatar','用户头像')->image('',80,80);
            $grid->column('user.nickname','用户昵称');
            $grid->column('profession.name','企业行业');
            $grid->column('category.name','企业类型');
            $grid->column('name');
            $grid->column('area');
            $grid->column('corporate_name');
            $grid->fixColumns(1);
            $grid->column('corporate_phone');
            $grid->column('audit_status')
                ->using([1 => '待审核',2 =>'已通过',3 => '已拒绝'])
                ->label([1 => 'danger',2 => 'success',3 => 'warning']);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->fixColumns(1);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();

                $filter->like('name')
                       ->width(3);
                $filter->equal('profession_id')
                       ->select(FirmProfession::getOption())
                       ->width(3);

                $filter->equal('category_id')
                       ->select(FirmCategory::getOption())
                        ->width(3);

                $filter->equal('is_cooperation','是否合作企业')
                       ->select([1 => '是',2 => '否'])
                       ->width(3);

                $filter->equal('audit_status')
                       ->select([1 => '待审核',2 =>'已通过',3 => '已拒绝'])
                       ->width(3);

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Firm(), function (Show $show) {
            $show->field('id');
            $show->field('user_id');
            $show->field('profession_id');
            $show->field('category_id');
            $show->field('name');
            $show->field('brand');
            $show->field('area');
            $show->field('cradle');
            $show->field('settled_status');
            $show->field('corporate_name');
            $show->field('idcard_reverse_photo');
            $show->field('idcard_front_photo');
            $show->field('business_license');
            $show->field('brand_certificate');
            $show->field('representative_name');
            $show->field('representative_idcard_reverse_photo');
            $show->field('representative_idcard_front_photo');
            $show->field('accredit_certificate');
            $show->field('corporate_phone');
            $show->field('audit_status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Firm(['profile']), function (Form $form) {
            $form->display('id');
            $form->selectTable('user_id','用户')
                 ->from(UserTable::make())
                 ->model(User::class,'id','nickname')
                 ->required();
            $form->select('profession_id','行业')
                 ->options(FirmProfession::getOption())
                 ->required();
            $form->select('category_id')
                 ->options(FirmCategory::getOption())
                 ->required();
            $form->text('name')
                 ->maxLength(100)
                 ->required();
            $form->text('area')
                 ->maxLength(100)
                 ->required();
            $form->text('corporate_name')
                 ->maxLength(60)
                 ->required();
            $form->image('idcard_reverse_photo')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->required();
            $form->image('idcard_front_photo')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->required();
            $form->image('business_license')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->required();
            $form->mobile('corporate_phone')
                 ->required();

            $form->datetime('consult_time','咨询时间')
                 ->customFormat(function ($value){
                    if ($value && $value>0){
                        return date('Y-m-d H:i:s',$value);
                    }

                    return  null;
                 })->saving(function ($value){
                    if ($value){
                        return strtotime($value);
                    }
                    return $value;
                 })->required();

            $form->multipleImage('profile.banners','轮播图')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->saving(function ($value){
                    return  empty($value) ? null : $value;
                });

            $form->file('profile.video_url','视频')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->saving(function ($value){
                    return (string)$value;
                });

            $form->display('profile.video_url','浏览视频')
                ->customFormat(function ($value){
                    $html = '<video width="320" height="240" controls>
    <source src="'.$value.'" type="video/mp4">
</video>';
                    return $html;
                });


            $form->editor('profile.intro','企业介绍')
                ->saving(function ($value){
                    return (string)$value;
                });
            $form->editor('profile.advantage','企业优势')
                ->saving(function ($value){
                    return (string)$value;
                });


            $form->text('profile.invest_amount','投资金额')
                ->maxLength(60)
                ->saving(function ($value){
                    return (string)$value;
                });

            $form->text('profile.invest_amount','加盟费用')
                ->maxLength(60)
                ->saving(function ($value){
                    return (string)$value;
                });
            $form->number('profile.store_num','门店数量')
                ->min(0)
                ->saving(function ($value){
                    return (int)$value;
                });


            $form->text('profile.set_up_time','成立时间')
                ->maxLength(60)
                ->saving(function ($value){
                    return (string)$value;
                });

            $form->list('profile.cooperation_area','合作区域');


            $form->text('profile.manage_method','管理方式')
                ->maxLength(60)
                ->saving(function ($value){
                    return (string)$value;
                });

            $form->text('profile.invest_crowd','投资人群')
                ->maxLength(60)
                ->saving(function ($value){
                    return (string)$value;
                });


            $form->list('profile.tags','企业标签');


            $form->image('profile.cover_one','1:1封面图')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->saving(function ($value){
                    return (string)$value;
                });


            $form->image('profile.cover_two','4:3封面图')
                ->disk('oss')
                ->autoUpload()
                ->removable(false)
                ->uniqueName()
                ->saveFullUrl()
                ->saving(function ($value){
                    return (string)$value;
                });


            $form->table('profile.contact','联系信息',function ($table){
                $table->text('area','区域');
                $table->text('name','姓名');
                $table->text('phone','电话');
            });

            $form->radio('is_cooperation','是否合作企业')
                ->options([1 =>'是',2 => '否'])
                ->required();

            $form->textarea('cooperation_desc','是否合作企业说明')
                ->rules('max:500',[
                    'max ' => '最多输入500字符'
                ])->saving(function ($value){
                    return (string)$value;
                });



            $form->radio('audit_status')
                ->options([1 => '待审核',2 => '已通过',3 => '已拒绝'])
                ->when(3,function (Form $form){
                    $form->textarea('reject_reason','拒绝原因')
                        ->saving(function ($value){
                            return (string)$value;
                        })->rules('max:255',['max' => '最多500字']);
                })->required();


            $form->saved(function (Form $form){
                if ($form->input('audit_status')==2){
                    DB::table('users')->where('id',$form->input('user_id'))->update(['auth' => 2]);
                    DB::table('firms')
                        ->where('id',$form->getKey())
                        ->update(['audit_time' => date('Y-m-d H:i:s')]);
                    Message::query()->create([
                        'type' => 1,
                        'content' => $form->input('name'). '成功入驻了花石木平台'
                    ]);
                    if ($form->input('profile')['intro'] && !$form->model()->audit_time){
                        $tts = new TtsService();
                        $task_id = $tts->ttsCreate(str_replace('&nbsp;','',strip_tags($form->input('profile')['intro'])));
                        DB::table('firm_profiles')
                            ->where('id',$form->getKey())
                            ->update([
                                'task_id' => $task_id,
                            ]);
                    }


                }

                if ($form->input('user_id') && $form->input('audit_status')==2){
                    event(new \App\Events\Message([
                        'user_id' =>  $form->input('user_id'),
                        'type' => 2,
                        'content' => '恭喜您申请的企业入驻已通过审核'
                    ]));
                }

                if ($form->input('user_id') && $form->input('audit_status')==3){
                    event(new \App\Events\Message([
                        'user_id' =>  $form->input('user_id'),
                        'type' => 2,
                        'content' => '您申请的企业入驻未通过审核'.$form->input('reject_reason')
                    ]));
                }
            });



            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
